import axios from'axios';
import qs from "qs"
import router from "../router/index.js"
import store from "../store/index.js"
import {success,warning,message,errors} from '../store/alert.js'



let token=""
axios.defaults.withCredentials=false;
axios.defaults.headers.common["Authorization"]=token;
//定义表头

//创建实例 指定基准路径
 var instance=axios.create({
	// baseURL:''
	baseURL:'http://127.0.0.1:8001'
})



//添加一个请求拦截器 自动读取 localstorage
instance.interceptors.request.use(
config => {
	let token=window.localStorage.getItem("token");
	
	console.log("token="+token)
	if(token){
		config.headers.Authorization=token
	}
	console.log("pppppppppppp")
	console.log(config)
	return config;
},
error => {
	return Promise.reject(error);
}
);

// //相应拦截器
instance.interceptors.response.use(
response => {
	console.log("拦截成功1："+response.status)
	return response;
},
error => {
	console.log("error拦截1："+error.response)
	if(error.response){
		switch(error.response.status){
		case 401:
			console.log("error拦截2："+error.response)
			errors("账号或密码错误")
			localStorage.setItem("token","")
			router.push("/login")
			break;
		case 403:
			errors("没有权限")
			
			break;
		default:
			errors("操作失败")
		
		}
		
	}
	return Promise.reject(error.response);
}
);

//get键值对提交
export let $get= (url,obj)=> {
	return instance.get(
	url,
	{params:obj}
	)
}

//post键值对提交
export let $postx =(url ,obj) => {
	
	let kv =qs.stringify(obj)
	console.log("postx="+kv)
	return instance.post(url,
	kv,{
		headers:{
			'Content-Type':'application/x-www-form-urlencoded;charset=utf8'
		}
	})
} 

//post json提交
export let $postj=(url,obj) => {
	return instance.post(
	url,
	obj,{
		headers:{
			'Content-Type':'application/json;charset=utf8'
		}
	}
	)
}

//post file body 带图片
export let $postf=(url,formDatas) => {
	return instance.post(
	url,
	formDatas,{
		headers:{
			'Content-Type':'multipart/form-data'
		}
	}
	)
}

export let $capt= (url)=> {
	return instance.get(
	url,
	{responseType:'blob'}
	)
}
